// 简单的数据库连接测试
const { Pool } = require('pg');

const pool = new Pool({
  host: process.env.DB_HOST || 'localhost',
  port: parseInt(process.env.DB_PORT || '5432'),
  database: process.env.DB_NAME || 'aide',
  user: process.env.DB_USER || 'postgres',
  password: process.env.DB_PASSWORD || 'unidt@123',
  max: 20,
  idleTimeoutMillis: 30000,
  connectionTimeoutMillis: 2000,
});

async function testConnection() {
  console.log('🔄 测试数据库连接...');
  
  try {
    const client = await pool.connect();
    console.log('✅ 数据库连接成功');
    
    // 删除旧表
    console.log('🗑️ 删除旧表...');
    await client.query(`DROP TABLE IF EXISTS suggestion_feedback CASCADE`);
    await client.query(`DROP TABLE IF EXISTS user_behaviors CASCADE`);
    console.log('✅ 删除旧表完成');
    
    // 创建用户行为表
    console.log('📋 创建用户行为表...');
    await client.query(`
      CREATE TABLE user_behaviors (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        action TEXT NOT NULL,
        entity_type TEXT NOT NULL,
        entity_id TEXT,
        metadata JSONB,
        timestamp TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
      )
    `);
    console.log('✅ 用户行为表创建完成');
    
    // 创建建议反馈表
    console.log('💬 创建建议反馈表...');
    await client.query(`
      CREATE TABLE suggestion_feedback (
        id TEXT PRIMARY KEY,
        user_id TEXT NOT NULL,
        suggestion_id TEXT NOT NULL,
        suggestion_type TEXT NOT NULL,
        action TEXT NOT NULL,
        rating INTEGER,
        feedback_text TEXT,
        created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
      )
    `);
    console.log('✅ 建议反馈表创建完成');
    
    // 插入测试数据
    console.log('📝 插入测试数据...');
    await client.query(`
      INSERT INTO user_behaviors (id, user_id, action, entity_type, metadata)
      VALUES ('test_1', 'default_user', 'task_create', 'task', '{"category": "work"}')
    `);
    
    await client.query(`
      INSERT INTO suggestion_feedback (id, user_id, suggestion_id, suggestion_type, action, rating)
      VALUES ('feedback_1', 'default_user', 'sugg_1', 'auto_schedule', 'accept', 4)
    `);
    console.log('✅ 测试数据插入完成');
    
    // 验证数据
    const behaviorCount = await client.query('SELECT COUNT(*) FROM user_behaviors');
    const feedbackCount = await client.query('SELECT COUNT(*) FROM suggestion_feedback');
    
    console.log(`📊 用户行为记录数: ${behaviorCount.rows[0].count}`);
    console.log(`📊 建议反馈记录数: ${feedbackCount.rows[0].count}`);
    
    client.release();
    console.log('🎉 数据库迁移完成!');
    
  } catch (error) {
    console.error('❌ 数据库操作失败:', error.message);
    console.error('错误详情:', error);
  } finally {
    await pool.end();
    process.exit(0);
  }
}

testConnection();
